#!/usr/bin/env python
#coding=utf-8

import json
import pandas as pd
import numpy as np
from pprint import pprint
from huaweicloudsdkcore.auth.credentials import GlobalCredentials
from huaweicloudsdkbss.v2.region.bss_region import BssRegion
from huaweicloudsdkcore.exceptions import exceptions
from huaweicloudsdkbss.v2 import *


from core.logger import logger


class HuaweiyunBillUtils(object):
    def __init__(self, account_name, accessKeyId, accessSecret):
        self.credentials = GlobalCredentials(accessKeyId, accessSecret) 
        self.account_name = account_name



    def get_bill(self, cycle):
        """
        获取所有账单
        """
        limit = 500
        offset = 0
        bill_infos = []

        client = BssClient.new_builder().with_credentials(self.credentials).with_region(BssRegion.value_of("cn-north-1")).build()
        while True:
            try:
                request = ListCustomerselfResourceRecordDetailsRequest()
                request.body = QueryResRecordsDetailReq(limit=limit, offset=offset, cycle=cycle, include_zero_record=False)
                response = client.list_customerself_resource_record_details(request)
                if response.status_code != 200:
                    logger.error(f"get huaweiyun bill:{self.account_name} failed")
                    return False
                
                bill_infos.extend(response.to_dict()["monthly_records"])
                if offset + limit > response.total_count:
                    break
                else:
                    offset += limit

            except Exception as e:
                logger.exception(f"get huaweiyun bill:{self.account_name} error =>{e}")
                return False
            
        logger.info(f"get huaweiyun bill:{self.account_name} success")
        return  bill_infos



    def get_bill_to_database(self, cycle):
        """
        获取所有账单，返回数据库格式
        """
        bill_datas = []
        bill_type = {
            1: "消费-新购",
            2: "消费-续订",
            3: "消费-变更",
            4: "退款-退订",
            5: "消费-使用",
            8: "消费-自动续订",
            9: "调账-补偿",
            14: "消费-服务支持计划月末扣费",
            16: "调账-扣费",
            18: "消费-按月付费",
            20: "退款-变更",
            23: "消费-节省计划抵扣",
            24: "退款-包年/包月转按需"
        }
        charge_mode = {
            1: "包年/包月",
            3: "按需",
            10: "预留实例"
        }
        
        
        # 获取所有账单
        bill_infos = self.get_bill(cycle)
        for bill_info in bill_infos:
            #清洗数据，华为云返回的字段值有的为None，会导致入库时报错
            bill_info = {
                key: value if value != None else ""
                for key, value in bill_info.items()
            }
            
            bill_tmp = {
                "bill_cycle": cycle,
                "cloud_platform": "华为云",
                "cost_unit": bill_info["enterprise_project_name"],
                "account_id": bill_info["customer_id"],
                "account_name": self.account_name,
                "owner_id": bill_info["customer_id"],
                "product_code": bill_info["cloud_service_type"],
                "product_name": bill_info["cloud_service_type_name"],
                "commodity_code": bill_info["resource_type_code"],
                "product_detail": bill_info["resource_type_name"],
                "subscription_type": charge_mode[bill_info["charge_mode"]],
                "service_period": 1,
                "service_period_unit": "月",
                "bill_type": bill_type[bill_info["bill_type"]],
                "bill_method": "华为云其他",
                "bill_item": bill_info["resource_type_name"],
                "instance_id": bill_info["res_instance_id"],
                "instance_name": bill_info["resource_name"],
                "resource_group": bill_info["root_resource_id"],
                "instance_tag": bill_info["resource_tag"],
                "instance_config": bill_info["product_spec_desc"],
                "instance_spec": bill_info["sku_code"],
                "internet_ip": "华为云无ip",
                "intranet_ip": "华为云无ip",
                "region": bill_info["region_name"],
                "zone": bill_info["region"],
                "pretax_gross_amount": bill_info["official_amount"],
                "invoice_discount": bill_info["discount_amount"],
                "deducted_by_coupons": bill_info["bonus_amount"],
                "pretax_amount": bill_info["consume_amount"],
                "payment_amount": bill_info["cash_amount"] + bill_info["flexipurchase_coupon_amount"] + bill_info["credit_amount"],
                "deducted_by_cash_coupons": bill_info["coupon_amount"],
                "deducted_by_prepaid_card": bill_info["stored_card_amount"],
                "outstanding_amount": bill_info["debt_amount"],
                "currency": "CNY",
            }
            
            if cycle == "2023-03":
                # yuchang要求过滤华为云2023-03月份测试券的账单：624462.44
                if bill_tmp["instance_id"] in [
                    "PSM202303280021",
                    "PSM202303280020",
                    "ff3c51b1-c47c-487f-997c-4e93a9183e82",
                    "5d6b306f-c938-404d-9006-746a073736b3",
                    "cf885d48-c1c1-41b2-84bb-6a9f9c9e5513",
                    "01154-239533907-0",
                    "01154-239533908-0",
                    "2d72a69f-2a67-46d2-b746-399d3361b77b",
                    "e8ff6f3b-2b1b-41a2-9a5f-ee6280b74a7a",
                    "bc1f616b-a83a-4503-92e3-b41a2679b764",
                    "b22d6a12-36e5-4190-8454-35578524a444",
                ] or bill_tmp["product_name"] in [
                    "数据仓库服务"
                ]:
                    logger.info(f"get huaweiyun bill:{bill_tmp['instance_id']} pretax_amount:{bill_tmp['pretax_amount']} continue")
                    continue
            
            bill_datas.append(bill_tmp)

        return bill_datas



    def get_bill_to_excel(self, cycle):
        """
        下载账单到excel文件
        """
        # bill_infos = self.get_bill(cycle)
        bill_infos = self.get_bill_to_database(cycle)
        
        df = pd.DataFrame(bill_infos)
        df.to_excel(f"{cycle}-{self.account_name}-database.xlsx", index=False)
        return True



def main():
    huaweiyun = HuaweiyunBillUtils("天冕", "tianmiantech", "TAZTC1YIBRKGIADUQFRX", "uHieUtiVHr0MrN0pnfXgnrLZpwgYFi1MvJNvADzv")
    huaweiyun.get_bill_to_excel("2023-01")
    # huaweiyun.get_bill_to_database("2023-01")
    



if __name__ == "__main__":
    main()

